<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  <link href="//fonts.useso.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java, gradle," />





  <link rel="alternate" href="/atom.xml" title="Lippi-浮生志" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.5.0" />






<meta name="description" content="最早接触依赖注入这个概念是在使用Spring框架的时候，一开始没太在意它，后面开发项目的过程中发现使用依赖注入可以降低代码的耦合性,Spring的依赖注入是通过反射机制实现的，而Dagger依赖注入是在编译期生成辅助的类，这些类继承特定父类或实现特定接口，程序在运行时 Dagger 加载这些辅助类，调用相应接口完成依赖生成和注入.">
<meta property="og:type" content="article">
<meta property="og:title" content="Dagger依赖注入浅析">
<meta property="og:url" content="http://www.ezlippi.com/blog/2015/08/dagger-dependency-injection.html">
<meta property="og:site_name" content="Lippi-浮生志">
<meta property="og:description" content="最早接触依赖注入这个概念是在使用Spring框架的时候，一开始没太在意它，后面开发项目的过程中发现使用依赖注入可以降低代码的耦合性,Spring的依赖注入是通过反射机制实现的，而Dagger依赖注入是在编译期生成辅助的类，这些类继承特定父类或实现特定接口，程序在运行时 Dagger 加载这些辅助类，调用相应接口完成依赖生成和注入.">
<meta property="og:updated_time" content="2016-02-29T13:11:57.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Dagger依赖注入浅析">
<meta name="twitter:description" content="最早接触依赖注入这个概念是在使用Spring框架的时候，一开始没太在意它，后面开发项目的过程中发现使用依赖注入可以降低代码的耦合性,Spring的依赖注入是通过反射机制实现的，而Dagger依赖注入是在编译期生成辅助的类，这些类继承特定父类或实现特定接口，程序在运行时 Dagger 加载这些辅助类，调用相应接口完成依赖生成和注入.">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>

  <title> Dagger依赖注入浅析 | Lippi-浮生志 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?340874ba9357cbe81570aa4ac1185941";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>






  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
<script>
(function(){
    var bp = document.createElement('script');
    bp.src = '//push.zhanzhang.baidu.com/push.js';
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
            
<div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Lippi-浮生志</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-th fa-fw"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-user fa-fw"></i> <br />
            
            关于
          </a>
        </li>
      

      
      
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'fLM9qfxyerC6njvM7usy','2.0.0');
</script>



    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Dagger依赖注入浅析
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2015-08-13T00:00:00+08:00" content="2015-08-13">
              2015-08-13
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/gradle/" itemprop="url" rel="index">
                    <span itemprop="name">gradle</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/blog/2015/08/dagger-dependency-injection.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="/blog/2015/08/dagger-dependency-injection.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
	
	<span id="busuanzi_container_page_pv" class="post-meta-item-text">
		&nbsp; | &nbsp;  
	    <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Hits
	</span>
        </div>
      </header>
    
	


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>最早接触依赖注入这个概念是在使用Spring框架的时候，一开始没太在意它，后面开发项目的过程中发现使用依赖注入可以降低代码的耦合性,Spring的依赖注入是通过反射机制实现的，而Dagger依赖注入是在编译期生成辅助的类，这些类继承特定父类或实现特定接口，程序在运行时 Dagger 加载这些辅助类，调用相应接口完成依赖生成和注入.</p>
<a id="more"></a>
<h2 id="什么是控制反转？"><a href="#什么是控制反转？" class="headerlink" title="什么是控制反转？"></a>什么是控制反转？</h2><p>比如你有一个DataProcessor类，DataProcessor里有一个DataFinder对象，用于查找数据，DataFinder是一个接口，它有一个实现类:IndexDataFinder,如果你要使用DataFinder来查找数据，传统的做法是在DataProcessor构造器里新建一个DataFinder对象，然后再调用DataFinder的findData方法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">DataProcessor</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.dataFinder = <span class="keyword">new</span> IndexDataFinder();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在上述的实现中，DataProcessor就和DataFinder紧密的耦合在一起．假设后来DataFinder又有一个新的实现类SQLDataFinder,根据需求来选择相应的实现，这时候你要怎么做呢？传统的做法就是给构造器传递一个int参数，根据参数的值来初始化DataFinder,还要处理异常参数如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">DataProcessor</span><span class="params">(<span class="keyword">int</span> dataFinderIndex)</span></span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(dataFinderIndex == <span class="number">0</span>)&#123;</span><br><span class="line">		<span class="keyword">this</span>.dataFinder = <span class="keyword">new</span> IndexDataFinder();	</span><br><span class="line">	&#125;<span class="keyword">else</span> <span class="keyword">if</span>(dataFinderIndex == <span class="number">1</span>)&#123;</span><br><span class="line">		<span class="keyword">this</span>.dataFinder = <span class="keyword">new</span> SQLDataFinder();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样子虽然代码变得简单，但是DataProcessor类仍然依赖于具体的实现，实际上DataProcessor不应该有这么多的控制逻辑，它只需要负责调用dataFinder的方法来完成它的逻辑，至于是什么类型的DataFinder它不应该考虑．我们试着将控制DataFinder的任务交给客户：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">DataProcessor</span><span class="params">(DataFinder dataFinder)</span></span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.dataFinder = dataFinder;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样DataProcessor就不用依赖具体的实现了，不用管到底是哪种类型的DataFinder,也就是说将选择DataFinder的控制权交给了客户端，实现了”控制反转”．控制反转只是一个概念而已，依赖注入是他的一种实现方法，依赖注入就是将实例变量传递到一个对象中去，依赖注入的方法有两种：构造器注入和setter方法注入．</p>
<h2 id="Dagger依赖注入"><a href="#Dagger依赖注入" class="headerlink" title="Dagger依赖注入"></a>Dagger依赖注入</h2><p>Spring IoC和Google Guice的依赖注入都很有名，但它们都是使用Java的反射机制来实现的，这对性能要求比较高的Android平台来说就不太适合了，于是Dagger应运而生.</p>
<h3 id="编译期"><a href="#编译期" class="headerlink" title="编译期"></a>编译期</h3><p>Dagger在编译时使用注解处理工具(APT)对所有的类进行扫描，这里包括两个工具InjectAdapterProcessor和ModuleAdapterProcessor,InjectAdapterProcessor会扫描所有的被@inject注解的元素，包括静态域，实例域和构造器，然后根据这几个元素生成一个内部对象InjectedClass，它的定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">InjectedClass</span> </span>&#123;</span><br><span class="line">	<span class="keyword">final</span> TypeElement type;</span><br><span class="line">	<span class="keyword">final</span> List&lt;Element&gt; staticFields;</span><br><span class="line">	<span class="keyword">final</span> ExecutableElement constructor;</span><br><span class="line">	<span class="keyword">final</span> List&lt;Element&gt; fields;</span><br><span class="line">	..............</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>根据域是否是静态域注入方式会有不同，非静态域生成InjectAdapter对象并保存在同个被注入类同个目录下，比如被注入的类为A,生成的类名称为A$$InjectAdapter,InjectAdapter包含了所有需要注入的实例域和构造器参数的信息．如果被注解的是静态域，则生成A$$StaticInjection.这里需要注意的是如果你是在构造函数上用@inject注解而且构造函数有其他参数，你需要给这些参数添加@inject注解或者在Module中提供provide方法（下面会讲到Module）．InjectAdapter类的生成Dagger用到了JavaPoet这个用于生成Java源文件的类库，用法简介：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">MethodSpec main = MethodSpec.methodBuilder(<span class="string">"main"</span>)</span><br><span class="line">.addModifiers(Modifier.PUBLIC, Modifier.STATIC)</span><br><span class="line">.returns(<span class="keyword">void</span>.class)</span><br><span class="line">.addParameter(String[].class, <span class="string">"args"</span>)</span><br><span class="line">.addStatement(<span class="string">"$T.out.println($S)"</span>, System.class, <span class="string">"Hello, JavaPoet!"</span>)</span><br><span class="line">.build();</span><br><span class="line"></span><br><span class="line">TypeSpec helloWorld = TypeSpec.classBuilder(<span class="string">"HelloWorld"</span>)</span><br><span class="line">.addModifiers(Modifier.PUBLIC, Modifier.FINAL)</span><br><span class="line">.addMethod(main)</span><br><span class="line">.build();</span><br><span class="line"></span><br><span class="line">JavaFile javaFile = JavaFile.builder(<span class="string">"com.example.helloworld"</span>, helloWorld)</span><br><span class="line"> .build();</span><br><span class="line"></span><br><span class="line">javaFile.writeTo(System.out);</span><br></pre></td></tr></table></figure>
<p>上面这种过注入依赖的方法适合我们自己编写的类，如果是第三方类库的话你没有修改它的源代码给它的构造器或者域添加@inject注解，这时候就需要使用第二种注入依赖的方法.通过新建一个用@Module注解的类，这个类告诉Dagger编译期哪些类要注入依赖，这个Module包含哪些子Module，通过编写provide方法来生成一些依赖实例．具体用法举例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Module</span>(</span><br><span class="line">	injects = CoffeeApp.class<span class="comment">//表示CoffeeApp这个类需要注入依赖</span></span><br><span class="line">	includes = PumpModule.class<span class="comment">//包括PumpModule这个Module</span></span><br><span class="line">	)	</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DripCoffeeModule</span> </span>&#123;</span><br><span class="line">	<span class="comment">//所有需要被注入的实例都用@Provides方法提供</span></span><br><span class="line">	<span class="annotation">@Provides</span> <span class="annotation">@Singleton</span> <span class="function">Heater <span class="title">provideHeater</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		  <span class="keyword">return</span> <span class="keyword">new</span> ElectricHeater();</span><br><span class="line">	 &#125;</span><br><span class="line">	<span class="comment">//方法可以有参数，前提是这个参数能够被注入</span></span><br><span class="line">	<span class="annotation">@Provides</span> <span class="function">Pump <span class="title">providePump</span><span class="params">(Heater heater)</span> </span>&#123;</span><br><span class="line">		 <span class="keyword">return</span> <span class="keyword">new</span> Thermosiphon(heater);	</span><br><span class="line">	 &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>编译时Dagger编译期扫描所有被@Provides注解的方法，然后扫描它所在的类是否被＠Module注解，根据Module注解的参数injects,includes,complete,library生成ModuleAdapter类，保存为［Module名称］$$ModuleAdapter的形式,内部使用的是generateModuleAdapter方法，定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> JavaFile <span class="title">generateModuleAdapter</span><span class="params">(TypeElement type,</span><br><span class="line">  Map&lt;String, Object&gt; module, List&lt;ExecutableElement&gt; providerMethods)</span> </span>&#123;</span><br><span class="line">Object[] injects = (Object[]) module.get(<span class="string">"injects"</span>);</span><br><span class="line">Object[] includes = (Object[]) module.get(<span class="string">"includes"</span>);</span><br><span class="line"><span class="keyword">boolean</span> complete = (Boolean) module.get(<span class="string">"complete"</span>);</span><br><span class="line"><span class="keyword">boolean</span> library = (Boolean) module.get(<span class="string">"library"</span>);</span><br><span class="line"><span class="comment">//省略了其他部分</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行时，在 Application 或某个具体模块的初始化处，使用ObjectGraph类来加载部分依赖(实质上是利用编译时生成的ModuleAdapters加载了所有的ProvidesBinding)，形成一个不完整的依赖关系图。 这个不完整的依赖关系图生成之后，就可以调用ObjectGraph的相应函数来获取实例和注入依赖了。实现依赖注入的函数有两个：<code>ObjectGraph.get(Class&lt;T&gt; type)</code>函数，用于直接获取对象；<code>ObjectGraph.inject(T instance)</code>函数，用于对指定对象进行属性的注入。在这些获取实例和注入依赖的过程中，如果用到了还未加载的依赖，程序会自动对它们进行加载(实质上是加载的编译时生成的InjectAdapter)。在此过程中，内存中的 DAG 也被补充地越来越完整。</p>
<p>简单介绍一些Dagger的Binding 类，它相当于依赖关系 DAG 图中的节点，依赖关系 DAG 图中得每一个节点都有一个由 APT 生成的继承自 Binding 的类与之对应，而依赖关系 DAG 图中的每一个节点与Host和Dependency一一对应，所以每个Host或Dependency必然有一个由 APT 生成的继承自 Binding 的子类与之对应，Binding.java 实现了两个接口，第一个是 javax 的Provider接口，此接口提供了 get() 函数用于返回一个Dependency实例，当然也可以是Host实例。第二个接口是 Dagger 中的MembersInjector接口，此接口提供了 injectMembers() 用来向Host对象中注入Dependency。<br>单纯的DependencyBinding只要实现Provider接口，在 get() 函数中返回自己的实例即可。单纯的HostBinding只要实现MembersInjector，在 injectMembers() 函数中调用DependencyBinding的 get() 函数得到依赖，然后对自己的依赖进行注入即可。如果一个类既是Host又是Dependency，则与它对应的Binding这两个接口都需要实现。</p>
<p>还是之前那个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CoffeeApp</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">  <span class="annotation">@Inject</span> CoffeeMaker coffeeMaker;</span><br><span class="line"></span><br><span class="line">  <span class="annotation">@Override</span> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		coffeeMaker.brew();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	<span class="comment">//建立依赖关系图</span></span><br><span class="line">	ObjectGraph objectGraph = ObjectGraph.create(<span class="keyword">new</span> DripCoffeeModule());</span><br><span class="line">	<span class="comment">//调用objectGraph．get(CoffeeApp.class)来获取一个CoffeeApp实例</span></span><br><span class="line">	CoffeeApp coffeeApp = objectGraph.get(CoffeeApp.class);</span><br><span class="line">	coffeeApp.run();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>CoffeeMaker的定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CoffeeMaker</span> </span>&#123;</span><br><span class="line">  <span class="annotation">@Inject</span> Lazy&lt;Heater&gt; heater; </span><br><span class="line">  <span class="annotation">@Inject</span> Pump pump;</span><br><span class="line"></span><br><span class="line">	 <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">brew</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	 heater.get().on();</span><br><span class="line">	 pump.pump();</span><br><span class="line">	 System.out.println(<span class="string">" [_]P coffee! [_]P "</span>);</span><br><span class="line">	 heater.get().off();</span><br><span class="line">	 &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<pre><code>这样在运行中Dagger会自动注入CoffeeMaker实例以及它依赖的对象heater和pump.
</code></pre>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java-gradle/" rel="tag">#java, gradle</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2015/07/gradle-tasks-guide.html" rel="next" title="彻底理解Gradle的任务">
                <i class="fa fa-chevron-left"></i> 彻底理解Gradle的任务
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2015/08/latex-fonts-settings.html" rel="prev" title="Latex中英文环境设置">
                Latex中英文环境设置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="/blog/2015/08/dagger-dependency-injection.html"
     data-title="Dagger依赖注入浅析"
     data-content=""
     data-url="http://www.ezlippi.com//blog/2015/08/dagger-dependency-injection.html">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="/blog/2015/08/dagger-dependency-injection.html"
           data-title="Dagger依赖注入浅析" data-url="http://www.ezlippi.com//blog/2015/08/dagger-dependency-injection.html">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="EZLippi" />
          <p class="site-author-name" itemprop="name">EZLippi</p>
          <p class="site-description motion-element" itemprop="description">Easy Lippi</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">63</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>
          
          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">69</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/EZLippi" target="_blank">
                  
                    <i class="fa fa-github"></i> GitHub
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/ouyanglip" target="_blank">
                  
                    <i class="fa fa-weibo"></i> weibo
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/lippi-ouyang" target="_blank">
                  
                    <i class="fa fa-weibo"></i> zhihu
                  
                </a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
            <p class="site-author-name">友情链接</p>
            
              <span class="links-of-author-item">
                <a href="http://szhshp.org" target="_blank">szhshp的博客</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/lippi-ouyang" target="_blank">友链出租</a>
              </span>
            
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是控制反转？"><span class="nav-number">1.</span> <span class="nav-text">什么是控制反转？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Dagger依赖注入"><span class="nav-number">2.</span> <span class="nav-text">Dagger依赖注入</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#编译期"><span class="nav-number">2.1.</span> <span class="nav-text">编译期</span></a></li></ol></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2014 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">EZLippi</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
   托管在 -
  <a class="theme-link" href="https://github.com/EZLippi/EZLippi.github.io">
    Github
  </a>

</div>
<div class="theme-info">
<span id="busuanzi_container_site_pv">
    &nbsp; | &nbsp;本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>



      </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  


  



  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=0.5.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=0.5.0"></script>



  
  

  
  
<script type="text/javascript" src="/js/src/scrollspy.js?v=0.5.0"></script>

<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    NexT.motion.middleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');

      if (CONFIG.sidebar.display === 'post' || CONFIG.sidebar.display === 'always') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          NexT.utils.displaySidebar();
        }
      }
    };
  });
</script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=0.5.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"ezlippi"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  





  
  

  
  


</body>
</html>
